import * as fs from 'fs';
import * as path from 'path';
import { AccountService } from './account-service';
import { PlatformService } from './platform-service';

interface UploadTask {
  id: string;
  filePath: string;
  fileName: string;
  fileSize: number;
  duration: number;
  title: string;
  description: string;
  tags: string[];
  thumbnail?: string;
  status: 'pending' | 'uploading' | 'processing' | 'completed' | 'failed';
  progress: number;
  platformResults: Map<string, { status: string; url?: string; error?: string }>;
}

export class UploadService {
  private accountService: AccountService;
  private platformService: PlatformService;
  private uploadTasks: Map<string, UploadTask> = new Map();

  constructor() {
    this.accountService = new AccountService();
    this.platformService = new PlatformService();
  }

  async uploadVideo(filePath: string, metadata: any): Promise<string> {
    const stats = fs.statSync(filePath);
    const taskId = this.generateTaskId();
    
    const task: UploadTask = {
      id: taskId,
      filePath,
      fileName: path.basename(filePath),
      fileSize: stats.size,
      duration: metadata.duration || 0,
      title: metadata.title || '',
      description: metadata.description || '',
      tags: metadata.tags || [],
      thumbnail: metadata.thumbnail,
      status: 'pending',
      progress: 0,
      platformResults: new Map()
    };

    this.uploadTasks.set(taskId, task);
    
    // 开始上传流程
    this.processUpload(taskId);
    
    return taskId;
  }

  async publishVideo(videoId: string, platforms: string[]): Promise<void> {
    const task = this.uploadTasks.get(videoId);
    if (!task) {
      throw new Error('Video task not found');
    }

    // 检查每个平台的账号状态
    for (const platformId of platforms) {
      const account = await this.accountService.getAccountByPlatform(platformId);
      if (!account) {
        task.platformResults.set(platformId, {
          status: 'failed',
          error: '未找到已登录的账号'
        });
        continue;
      }

      // 开始发布到该平台
      this.publishToPlatform(videoId, platformId, account);
    }
  }

  private async processUpload(taskId: string) {
    const task = this.uploadTasks.get(taskId);
    if (!task) return;

    task.status = 'uploading';
    
    // 模拟上传进度
    for (let i = 0; i <= 100; i += 10) {
      await this.delay(500);
      task.progress = i;
      
      // 发送进度到前端
      const { BrowserWindow } = require('electron');
      const windows = BrowserWindow.getAllWindows();
      windows.forEach((window: any) => {
        window.webContents.send('upload-progress', {
          taskId,
          progress: i,
          status: task.status
        });
      });
    }

    task.status = 'processing';
    await this.delay(2000);
    task.status = 'completed';
  }

  private async publishToPlatform(videoId: string, platformId: string, account: any) {
    const task = this.uploadTasks.get(videoId);
    if (!task) return;

    try {
      // 模拟发布过程
      task.platformResults.set(platformId, { status: 'publishing' });
      
      // 发送进度到前端
      const { BrowserWindow } = require('electron');
      const windows = BrowserWindow.getAllWindows();
      windows.forEach((window: any) => {
        window.webContents.send('publish-progress', {
          videoId,
          platformId,
          status: 'publishing'
        });
      });

      // 模拟API调用
      await this.delay(3000);

      // 生成模拟的发布结果
      const mockUrl = `https://${platformId}.com/video/${Date.now()}`;
      
      task.platformResults.set(platformId, {
        status: 'success',
        url: mockUrl
      });

      // 发送完成通知
      windows.forEach((window: any) => {
        window.webContents.send('publish-progress', {
          videoId,
          platformId,
          status: 'success',
          url: mockUrl
        });
      });

    } catch (error) {
      task.platformResults.set(platformId, {
        status: 'failed',
        error: (error as Error).message
      });
    }
  }

  getUploadTask(taskId: string) {
    return this.uploadTasks.get(taskId);
  }

  getAllTasks() {
    return Array.from(this.uploadTasks.values());
  }

  private generateTaskId(): string {
    return Date.now().toString(36) + Math.random().toString(36).substring(2);
  }

  private delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  // 验证视频文件
  validateVideoFile(filePath: string): { valid: boolean; error?: string } {
    const ext = path.extname(filePath).toLowerCase();
    const allowedExtensions = ['.mp4', '.avi', '.mov', '.mkv', '.flv'];
    
    if (!allowedExtensions.includes(ext)) {
      return { valid: false, error: '不支持的文件格式' };
    }

    const stats = fs.statSync(filePath);
    const maxSize = 2 * 1024 * 1024 * 1024; // 2GB
    
    if (stats.size > maxSize) {
      return { valid: false, error: '文件过大，最大支持2GB' };
    }

    return { valid: true };
  }
}
